﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace GotLyrics.LyricGrabbers
{
    public class LeosLyricsGrabber : LyricGrabber
    {
        public override string WebSiteUrl
        {
            get { return "http://www.leoslyrics.com/"; }
        }

        protected override string GrabLyric(LyricGrabberContext context)
        {
            string url = string.Format("http://api.leoslyrics.com/api_search.php?auth=duane&artist={0}&songtitle={1}",
                                       HttpUtility.UrlEncode(context.Tags.Artist),
                                       HttpUtility.UrlEncode(context.Tags.Title));

            string response = WebClient.DownloadString(url);

            if (IsValidResponse(response))
            {
                string pattern = "<result\\ id=\"(?<id>.+?)\"\\ hid=\"(?<hid>.+?)\"\\ exactMatch=\"true\">";

                Match m = Regex.Match(response, pattern);

                if (m.Success)
                {
                    url = string.Format("http://api.leoslyrics.com/api_lyrics.php?auth=duane&hid={0}",
                                        m.Groups["hid"].Value);

                    response = WebClient.DownloadString(url);

                    if (IsValidResponse(response))
                    {
                        pattern = "<text>(?<lyrics>.+)</text>";
                        m = Regex.Match(response, pattern, RegexOptions.Singleline);

                        if (m.Success)
                        {
                            // Remove the &#xD; from the text
                            string lyrics = m.Groups["lyrics"].Value;

                            pattern = "&#xD;\\r\\n(\\s+)?";

                            lyrics = Regex.Replace(lyrics, pattern, "\r\n");

                            return lyrics;
                        }
                    }
                }

            }

            return null;
        }

        private bool IsValidResponse(string response)
        {
            return !string.IsNullOrEmpty(response) &&
                   response.IndexOf("<response code=\"0\">SUCCESS</response>") != -1;
        }
    }
}
